package com.noah.bee.core.util;

import com.thetransactioncompany.jsonrpc2.JSONRPC2ParseException;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class JsonRPC2Util {

	private static final Logger logger = LoggerFactory.getLogger(JsonRPC2Util.class);

	public static String generateMsg(String id, String method,
			Map<String, Object> params) {
		// Create a new JSON-RPC 2.0 request
		JSONRPC2Request reqOut = new JSONRPC2Request(method, params, id);

		// Serialise the request to a JSON-encoded string
		String jsonString = reqOut.toString();
		logger.info(jsonString);
		return jsonString;
	}
	
	/*
	 * 
	 * @param jsonString
	 * @return JSONRPC2Request
	 * @throws JSONRPC2ParseException
	 * usage:
	 * method     : reqIn.getMethod()
	 * parameters : reqIn.getNamedParams()
	 * id         : reqIn.getID()
	 */
	public static JSONRPC2Request parseRequestMsg(String jsonString) throws JSONRPC2ParseException{

		try {
			 return JSONRPC2Request.parse(jsonString);

		} catch (JSONRPC2ParseException e) {
			logger.error("parseRequestMsg error", e);
			throw e;
		}

	}
	
	/*
	 * 
	 * @param jsonString
	 * @return JSONRPC2Response
	 * @throws JSONRPC2ParseException
	 * usage:
	 * method     : reqIn.getMethod()
	 * parameters : reqIn.getNamedParams()
	 * id         : reqIn.getID()
	 */
	public static JSONRPC2Response parseResponseMsg(String jsonString) throws JSONRPC2ParseException{

		try {
			 return JSONRPC2Response.parse(jsonString);

		} catch (JSONRPC2ParseException e) {
			logger.error(e.getMessage());
			throw e;
		}

	}
	
	
	public static String genarateResponse(String result,JSONRPC2Request reqIn) {

//		String result = "payment-id-001";
		JSONRPC2Response respOut = new JSONRPC2Response(result, reqIn.getID());
		// Serialise response to JSON-encoded string
		String response = respOut.toString();
		logger.info(response);
		return response;
	}
}
